#include <signal.h>
#include <iostream>
#include <string>

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
#include <workflow/HttpUtil.h>

using std::cout;
using std::endl;
using std::string;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    cout << "sighandler is processing" << endl;
    waitGroup.done();
}

void httpCallback(WFHttpTask * serverTask)
{
    cout << "server httpCallback is running" << endl;
}

void process(WFHttpTask * serverTask)
{
    cout << "process funciton is running\n";
    //设置任务的回调函数
    serverTask->set_callback(httpCallback);

    int state = serverTask->get_state();
    int error = serverTask->get_error();
    cout << "state:" << state << endl;
    
    switch(state) {
    case WFT_STATE_TOREPLY:
        break;
    case WFT_STATE_NOREPLY:
        printf("Error: %s\n",
            WFGlobal::get_error_string(state, error));
        break;
    }

    if(state != WFT_STATE_TOREPLY) {
        return;
    }

    //解析请求
    auto req = serverTask->get_req();//已经有了
    auto resp = serverTask->get_resp();//需要生成

    printf("%s %s %s\n", req->get_method()
           , req->get_request_uri()
           , req->get_http_version());

    //生成响应 html
    string html("<html>");
    string firstline("<p>");
    firstline.append(req->get_method()).append(" ")
        .append(req->get_request_uri()).append(" ")
        .append(req->get_http_version()).append("</p>");
    resp->append_output_body(html.c_str(), html.size());
    resp->append_output_body(firstline.c_str(), firstline.size());

    protocol::HttpHeaderCursor cursor(req);
    string key, value, headers("<p>");
    while(cursor.next(key, value)) {
        headers.append(key).append(":").append(value).append("\n");
    }
    headers.append("</p>");
    resp->append_output_body(headers.c_str(), headers.size());
    string endhtml("</html>");
    resp->append_output_body(endhtml.c_str(), endhtml.size());


    //设置响应报文的起始行
    resp->set_http_version("HTTP/1.1");
    resp->set_status_code("200");
    resp->set_reason_phrase("OK");
    //设置响应报文的首部字段
    resp->add_header_pair("Content-Type", "text/html");

}

void test0()
{
    signal(SIGINT, sighandler);
    
    WFHttpServer server(process);

    if(server.start(8888) == 0) {
        waitGroup.wait();
        server.stop();
    } else {
        cout << "server cannot start" << endl;
    }
}


int main()
{
    test0();
    return 0;
}

